<?php
namespace app\index\controller;

use think\Controller;

class Service extends Controller
{
    protected $appid = '';//小程序id
    protected $appkey = '';//小程序key
    protected $mch_id = '';//商户号
    protected $mch_key = '';//支付秘钥

    
    public function __construct()
    {
        $this->appid = "wxd5d47d91e606786c";
        $this->appkey = "5bb70c07f3d2da95745124aeaa699ff0";
        $this->mch_id = "1611281066";
        $this->mch_key = "3a0a8dfdeae19033da914e8975815c60";
    }

    
    
    //进入小程序渲染前，获取用户唯一凭证u_token，每次请求时附带该参数。
    public function user_get_token(){
        $get = input('post.');
        $param['appid'] = $this->appid; //小程序id
        $param['secret'] = $this->appkey; //小程序密钥
        $param['js_code'] = $this->define_str_replace($get['code']);
        // $param['js_code'] = '0015vM0w38lJfZ2Zjy1w3zCOU315vM0i';
        $param['grant_type'] = 'authorization_code';
        $http_key = $this->httpCurl('https://api.weixin.qq.com/sns/jscode2session', $param, 'GET');
        $session_key = json_decode($http_key,true);//获取openid和session_key
        //dump($session_key);die;
        // print_r(http_build_query($param));
        if (!empty($session_key['session_key'])) {
            
            $data['session_key'] = $session_key['session_key'];
            $data['u_token'] = $session_key['openid'];
            //openid不存在则插入，存在则不处理
            $req = DB("weixin_user")->where(['u_token' => $data['u_token']])->find();
            if(empty($req)){
                DB("weixin_user")->insert(['u_token' => $data['u_token'],"openid" =>$data['u_token']]);
            }

            $result = ['code' => 200, "msg" => "操作成功", "data" => $data];
            echo json_encode($result);
        }else{
            dump($session_key);die;
            echo '获取session_key失败！';
        }

    }


    //获取手机号码（绑定移车贴）
    public function user_bind_phone(){
        $post = input('post.');
        // DB("logs")->insert(['logs' => json_encode($post)]);
        // die;
        // $post = ['u_token' => 'oxkCM4gClPsA2BzOKzA2L5UBF0aU','code'=>'51271e7f8ee87d90ad87af99e941b9b7cce5d38e85e63ed51a1852f3ab6f29a7','car_qr_id'=>4];
        $tmp = $this->getAccessToken();
        $tmptoken = json_decode($tmp);
        $token = $tmptoken->access_token;
        
        $data['code'] = $post['code'];
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
        
        $info = $this->http_request($url,json_encode($data),'json');
        // 一定要注意转json，否则汇报47001错误
        $tmpinfo = json_decode($info,true);

        $code = $tmpinfo['errcode'];
        
        if($code == '0'){
            $phone_info = $tmpinfo['phone_info'];
            //手机号
            $phoneNumber = $phone_info['phoneNumber'];
            
            //修改用户信息
            $weixin = DB("weixin_user")->where(['u_token' => $post['u_token']])->find();
            if(!empty($weixin)){
                $wei = $weixin['id'];
                DB("weixin_user")->where(['u_token' => $post['u_token']])->update(['phone' => $phoneNumber]);
            } else {
                $wei = DB("weixin_user")->insertGetId(['phone' => $phoneNumber,'u_token' => $post['u_token'],"openid" =>$post['u_token']]);
            }
            
            //添加绑定信息
            $date = date("Y-m-d H:i:s");
            //判断该二维码是否被绑定过，没绑定过添加绑定数据
            if(empty(DB("bind")->where(['qr_id'=>$post['car_qr_id']])->find())){
                $id = DB("bind")->insertGetId(['phone'=>$phoneNumber,'qr_id'=>$post['car_qr_id'],'user_id'=>$wei,'create_time'=> $date,'expire_is'=>1]);
            }
            
            //返回给前端的数据
            $req = [
                'id' =>$id,
             'car_qr_id' => $post['car_qr_id'],
            'real_phone' =>$phoneNumber,
            'call_real' => 1,
            'bind_time'=>$date,
            'expire_time'=>'',
            'expire_is'=>1
            ];
            
            echo json_encode(['code'=>200,'msg'=>'请求成功','data'=>$req]);
            die();
        }else{
            echo json_encode(['code'=>$code,'msg'=>$tmpinfo['errmsg']]);
            die();
        }
        
    }

    

    //更改移车贴是否虚拟拨号
    public function change_call_real(){
        $get = input('post.');
        $u_token = $get['u_token'];
        $car_qr_id = $get['car_qr_id'];
        
        // $u_token = "oxkCM4gClPsA2BzOKzA2L5UBF0aU";
        // $car_qr_id = $get['car_qr_id'];

        if(DB("bind")->where(['qr_id' => $car_qr_id])->update(['call_real' => $get['call_real']]) !== false){
            $result = ['code' => 200, "msg" => "操作成功"];
        } else {
            $result = ['code' => 500, "msg" => "操作失败"];
        }

        echo json_encode($result);
    }

    //判断用户和移车码的状态关系
    public function car_qr_u_relation(){
        $get = input('post.');
        $u_token = $get['u_token'];
        $car_qr_id = $get['car_qr_id'];

        // $u_token = 'oxkCM4gClPsA2BzOKzA2L5UBF0aU';
        // $car_qr_id = 10;
        //获取当前用户的id
        $weiixn = DB("weixin_user")->where(['u_token' => $u_token])->find();

        $info = DB("bind")->alias('b')
        ->leftJoin("qrcode q", "b.qr_id=q.id")
        ->leftJoin("weixin_user w", "b.user_id=w.id")
        ->where(['b.qr_id' => $car_qr_id])
        ->field("b.*,w.phone as bind_phone,q.id as car_qr_id,b.create_time as bind_time")
        ->find();

        if(!empty($info)){
            //
            if($info['user_id'] == $weiixn['id']){
                //如果当前用户为该二维码绑定用户
                $datas = [
                'id' => $info['id'],
                'car_qr_id' => $info['qr_id'],
                'real_phone' => $info['phone'],
                'call_real' => $info['call_real'],
                'bind_time' => $info['bind_time'],
                'expire_time' => $info['expire_time'],
                'expire_is' => $info['expire_is']];
 
                $result = ['code' => 200, "msg" => "操作成功", "data" => ['car_qr_status' => 2,'car_qr_info_data' => $datas]];
            } else {
                //如果当前用户不是改二维码的绑定用户【拨号方】
                $result = ['code' => 200, "msg" => "操作成功", "data" => ['car_qr_status' => 3,'car_qr_info_data' => ['']]];
            }
            
        } else {
            $result = ['code' => 200, "msg" => "操作成功", "data" => ['car_qr_status' => 1,'car_qr_info_data'=>['']]];
        }
        echo json_encode($result);
    }

    //获取该微信用户绑定移车贴数据
    public function user_get_bind_list(){
        $param = input('post.');
        $u_token = $param['u_token'];
        // $u_token = "oxkCM4gClPsA2BzOKzA2L5UBF0aU";
        
        $list = DB("bind")->alias('b')
        ->leftJoin("qrcode q", "b.qr_id=q.id")
        ->leftJoin("weixin_user w", "b.user_id=w.id")
        ->where(['w.u_token' => $u_token])
        ->field("b.id,b.phone as real_phone,q.id as car_qr_id,b.create_time as bind_time,b.expire_time,b.expire_is,b.call_real")
        ->select();

        $result = ['code' => 200, "msg" => "操作成功", "data" => $list];
// dump($result);die;
        echo json_encode($result);
    }

    //更改绑定移车贴的手机号码
    public function change_bind_phone(){
        $get = input('post.');
        $u_token = $get['u_token'];
        $car_qr_id = $get['car_qr_id'];
        $phone_new = $get['phone_new'];

        if(DB("bind")->where(['qr_id' => $car_qr_id])->update(['phone' => $phone_new]) !== false){
            $result = ['code' => 200, "msg" => "操作成功"];
        } else {
            $result = ['code' => 201, "msg" => "操作失败"];
        }

        echo json_encode($result);
    }

    //注销该移车贴的绑定关系
    public function logout_bind(){
        $param = input('post.');
        $car_qr_id = $param['car_qr_id'];
        $u_token = $param['u_token'];
        // $car_qr_id = 1;
        // $u_token = "123456";        

        //查询绑定信息
        $bind = DB("bind")->alias('b')
        ->leftJoin("weixin_user w", "b.user_id=w.id")
        ->where(['b.qr_id' => $car_qr_id, "w.u_token" => $u_token])
        ->field("b.*")
        ->find();

        //删除绑定关系
        $re[] = DB("bind")->delete($bind['id']);

        if($re){
            $result = ['code' => 200, "msg" => "操作成功"];
        } else {
            $result = ['code' => 201, "msg" => "操作失败"];
        }
        echo json_encode($result);
    }
    

    //获取拨打的号码1:普通号2虚拟号
    public function get_u_call_phone(){
        $alibaba = new Alibaba;
        $post = input('post.');
        
        $car_qr_id = $post['car_qr_id'];
        // $car_qr_id = 10;
        $phone = DB("bind")->where(["qr_id"=>$car_qr_id])->find();
        
        if($phone['expire_is'] == 1){
            //二维码已到期
            $result = ['code' => 500, "msg" => "该移车服务已过期，无法转拨"];
        } else {
            if($phone['call_real'] == 2){
                //虚拟号
                $expiration = date("Y-m-d H:i:s",strtotime("+3 minutes"));
                $re = $alibaba->main($phone['phone'],$expiration);
            } else {
                //真实号码
                $re = $phone['phone'];
            }
            
            
            $result = ['code' => 200, "msg" => "操作成功", 'data' => ['call_phone' => $re]];
        }
        
        echo json_encode($result);
    }
   
   
   /**
    * 请求过程中因为编码原因+号变成了空格
    * 需要用下面的方法转换回来
    */
    public function define_str_replace($data)
   {
    return str_replace(' ','+',$data);
   }

  
   /**
  * 发送HTTP请求方法
  * @param string $url 请求URL
  * @param array $params 请求参数
  * @param string $method 请求方法GET/POST
  * @return array $data 响应数据
  */
 public function httpCurl($url, $params, $method = 'POST', $header = array(), $multi = false){
        date_default_timezone_set('PRC');
        $opts = array(
        CURLOPT_TIMEOUT  => 30,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER  => $header,
        CURLOPT_COOKIESESSION => true,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_COOKIE   =>session_name().'='.session_id(),
        );
        /* 根据请求类型设置特定参数 */
        switch(strtoupper($method)){
        case 'GET':
        // $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
        // 链接后拼接参数 & 非？
        $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
        break;
        case 'POST':
        //判断是否传输文件
        $params = $multi ? $params : http_build_query($params);
        $opts[CURLOPT_URL] = $url;
        $opts[CURLOPT_POST] = 1;
        $opts[CURLOPT_POSTFIELDS] = $params;
        break;
        default:
        throw new Exception('不支持的请求方式！');
        }
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if($error) throw new Exception('请求发生错误：' . $error);
        return $data;
   }

   public  function getAccessToken()
    {
        $appid = $this->appid;;
        $secret = $this->appkey;

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret."";

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
        exit();
    }

    public function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, TRUE);
            curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json'
            ));
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);

        return $output;
        exit();

    }

}
